<?php
require "common.php";

$username = $_POST['username'];
$password = $_POST['password'];


if (empty($username) || empty($password)) {
    echo jsonReturn(2, '用户名或密码不能为空');
    exit;
}

// 判断是否已经注册过
$sql = "select * from user where username = $username";

$query = mysqli_query($connect, $sql);

$user = mysqli_fetch_assoc($query);

if (empty($user)) {
    echo jsonReturn(2, '用户名不存在');
    exit;
}

// 验证密码是否正确
if (md5($password) != $user['password']) {
    echo jsonReturn(2, '密码错误');
    exit;
}

// echo jsonReturn(1, '登录成功');

//用户ID
$userId = $user['id'];
//6位随机数
$rand_str =  createRandStr();
//token
$token = md5($username.$password.$rand_str);
//签发时间
$create_time = time();
//过期时间
$expire_time = $create_time + 60;


// 判断数据库中有没有这个用户的token
$getTokenSql  = "select * from user_token where user_id = $userId";
//echo $getTokenSql;exit;
$result = mysqli_query($connect,$getTokenSql);
$data = mysqli_fetch_assoc($result);

if (empty($data)){
    $addTokenSql = "insert into user_token (user_id,rand_str,token,expire_time,create_time) values ($userId,'$rand_str','$token',$expire_time,$create_time)";
    $query = mysqli_query($connect,$addTokenSql);
}else{
    $updateTokenSql = "update user_token set rand_str = '$rand_str',token = '$token',expire_time = $expire_time,create_time = $create_time where user_id = $userId";
    $query = mysqli_query($connect,$updateTokenSql);

}
if ($query) {
    echo jsonReturn(1, '登录成功', ['token' => $token]);
} else {
    echo jsonReturn(2, '登录失败', ['token' => '']);
}
// 生成随机6位数
function createRandStr(){
    $str = "ABCDEFGHIJLMNOPQRSTUVWXYZ0123456789";
    $arr = [] ;
    for ($i = 0 ; $i < 6 ;$i++){
        $code = $str[mt_rand(0,34)];
        array_push($arr, $code);
    }
    return implode('', $arr);
}
